import React from 'react'
import {Row, Col, Button, Table, Input, Tag, Avatar, Modal, message} from 'antd'
// import { UserOutlined } from '@ant-design/icons';
import '../styles.css'
import Model from "./Model/index"
import ResetPassword from "./Model/resetPassword"
import axios from "axios";
import api from "../../../api/api";
import Addcompany from "../../Organization/CompanyManagement";

const {Search} = Input;


class AdministratorManagement extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modelData: {
                title: "新增",
                visible: false,
                type: 1,//新增:1,编辑: 2,
                gridList: {}
            },
            resetPasswordData: {
                title: "重置密码",
                visible: false,
                gridList: {}
            },
            data: [],
            pageNum: 1,
            pageSize: 10,
            total: 0
        };
    }

    componentDidMount() {
        this.getAdministratorList();
    }

    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            className: "elementHidden",
            key: 'id',
            width: '5%'
        },
        {
            title: '账号',
            dataIndex: 'loginAccount',
            key: 'loginAccount',
            width: '5%'
        },
        {
            title: '手机号',
            dataIndex: 'mobile',
            width: '5%',
            key: 'mobile'
        },
        {
            title: '权限编号',
            dataIndex: 'authorityId',
            className: "elementHidden",
            width: '5%',
            key: 'authorityId'
        },
        {
            title: '权限组',
            dataIndex: 'authorityName',
            width: '5%',
            key: 'authorityName'
        },
        {
            title: '账号状态',
            dataIndex: 'state',
            width: '5%',
            key: 'state',
            render: state => {
                //正常:0 停用:1
                let stateInfo = (state === "0" || state === 0) ? "禁用" : "启用";
                let color = (state === "0" || state === 0) ? "magenta" : "green";
                return (
                    <div>
                        <Tag color={color}>{stateInfo}</Tag>
                    </div>
                )
            }
        },
        {
            title: '更新时间',
            dataIndex: 'time',
            width: '5%',
            key: 'time'
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '20%',
            key: 'option',
            render: (text, record, index) => {
                console.log("record", record)
                if (record.authorityId == 1 || record.authorityId == 2) {
                    return (
                        <span>
                            <a className="optionMargin" onClick={() => this.onClickResetPassword(record)}>重置密码</a>
                          </span>
                    )
                } else {
                    return (
                        <span>
                            <a className="optionMargin"
                               onClick={() => this.onClickState(record)}>{record.state === "0" || record.state === 0 ? "启用" : "禁用"}</a>
                            <a className="optionMargin" onClick={() => this.onClickResetPassword(record)}>重置密码</a>
                            <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
                            <a className="optionMargin" onClick={() => this.onClickDelete(record.id)}>删除</a>
                          </span>
                    )
                }
            }
        }
    ];

    onRef = (value,ref) => {
        if(value == "resetPassword"){
            this.resetChild = ref;
        }else if (value == "detail"){
            this.child = ref
        }
    }

    getAdministratorList() {
        var that = this;
        axios.post(api.api_URL + "/admin/logininfo/queryDirectoryInfoByPage?orgCode=" + localStorage.getItem('orgCode') + "&orderType=desc&pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize, {
            "orgCode": localStorage.getItem('orgCode')
        }, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                message.error({content:"加载失败，请重新尝试！"})
                return;
            }
            let totalSize = res.data.data.list.totalSize;
            const dataList = [];
            for (let i = 0; i < res.data.data.list.content.length; i++) {
                let resContent = res.data.data.list.content[i];
                const content = {};
                content.key = (i + 1);
                content.id = resContent.id;
                content.loginAccount = resContent.loginAccount;
                content.mobile = resContent.mobile;
                content.authorityName = resContent.authorityName;
                content.authorityId = resContent.authorityId;
                content.state = resContent.activeFlag;
                content.time = resContent.createTime;
                dataList[i] = content;

            }
            console.log(dataList);

            that.setState({
                data: dataList,
                total: totalSize
            })
        }).catch(function (err) {
            message.error({content:"加载失败，请重新尝试！"})
            console.log(err);
        });
    }

    //分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getAdministratorList()
        });

    }

    //添加
    onClickAdd(item) {
        this.setState({
            modelData: {
                title: "新增管理员",
                type: 3,
                visible: true,
                gridList: item
            }
        }, () => {
            this.child.clearData()
        });
    }

    //编辑
    onClickEdit(item) {
        this.setState({
            modelData: {
                title: "编辑管理员",
                type: 2,
                visible: true,
                gridList: item
            }
        }, () => {
            this.child.initEditData()
        });
    }

    //启用/停用状态
    onClickState(item) {
        let that = this;
        console.info("启用/禁用");
        let title = "启用/禁用";
        let modifyState = 0;
        if (item.state === "0" || item.state === 0) {
            title = "启用"
            modifyState = 1;
        } else {
            title = "禁用"
            modifyState = 0;
        }
        let configModel = Modal.confirm({
            title: title,
            content: '是否确认' + title + '？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    axios.post(api.api_URL + "/admin/logininfo/updateLoginInfo", {
                        "activeFlag": modifyState,
                        "id": item.id
                    }, {
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        if (item.state === "0" || item.state === 0) {
                            //启用
                            if (res.data.code != 1) {
                                message.error({content:"启用失败，请重新尝试！"})
                                return;
                            }
                            message.success({content:"启用成功！"})
                        } else {
                            //禁用
                            if (res.data.code != 1) {
                                message.error({content:"禁用失败，请重新尝试！"})
                                return;
                            }
                            message.success({content:"禁用成功！"})
                        }
                        that.setState({
                            data: []
                        })
                        that.getAdministratorList();
                        configModel.destroy();
                    }).catch(function (err) {
                        if (item.state === "0" || item.state === 0) {
                            //启用
                            if (res.data.code != 1) {
                                message.error({content:"启用失败，请重新尝试！"})
                                return;
                            }
                        } else {
                            //禁用
                            if (res.data.code != 1) {
                                message.error({content:"禁用失败，请重新尝试！"})
                                return;
                            }
                        }
                        console.log(err);
                        configModel.destroy();
                    });
                }).catch((e) => console.warn(e));

            },
            onCancel() {
            },
        })
    }

    //重置密码
    onClickResetPassword(item) {
        let that = this;
        console.info("");
        let title = "重置密码";


        this.setState({
            resetPasswordData: {
                title: "重置密码",
                visible: true,
                gridList: item
            }
        }, () => {
            this.resetChild.initEditData()
        });

        return;
        let configModel = Modal.confirm({
            title: title,
            content: '是否确认' + title + '为1234567890？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    axios.post(api.api_URL + "/admin/logininfo/resetLoginPassword", {
                        "id": item.id
                    }, {
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        if (res.data.code != 1) {
                            message.error({content:"重置密码失败！"})
                            return;
                        }
                        message.success({content:"重置密码成功！"})
                        configModel.destroy();
                    }).catch(function (err) {
                        message.error({content:"重置密码失败！"})
                        console.log(err);
                        configModel.destroy();
                    });
                }).catch((e) => console.warn(e));

            },
            onCancel() {
            },
        })
    }


    //删除
    onClickDelete(id) {
        console.info("删除===", id);

        if (id == "") {
            message.error({content:"删除失败，请重新尝试 ！"})
        }
        let that = this;

        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    axios.get(api.api_URL + "/admin/logininfo/deleteLoginInfo?loginInfoId=" + id, {
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        if (res.data.code != 1) {
                            message.error({content:"删除失败，请重新尝试 ！"})
                            return;
                        }
                        message.success({content:"删除成功！"})

                        that.setState({
                            data: []
                        })
                        that.getAdministratorList();
                        configModel.destroy();
                    }).catch(function (err) {
                        message.error({content:"删除失败，请重新尝试 ！"})
                        console.log(err);
                        configModel.destroy();
                    });
                }).catch((e) => console.warn(e));

            },
            onCancel() {
            },
        })

    }

    handleOk = e => {
        console.log(e);
        this.setState({
            modelData: {
                visible: false
            },
        });
    }
    handleCancel = e => {
        this.setState({
            modelData: {
                visible: false
            },
        }, () => {
            this.refresh()
        });
    }

    handleCancelReset = e => {
        this.setState({
            resetPasswordData: {
                visible: false
            },
        }, () => {
            // this.refresh()
        });
    }

    refresh() {
        this.getAdministratorList()
    }

    render() {

        return (
            <div className="girdBg">
                <Row className="searchBox">
                    <Col span={20}>
                        {/*<Search style={{width: 200, marginLeft: 30}}*/}
                        {/*placeholder="请输入"*/}
                        {/*onSearch={value => console.log(value)}*/}
                        {/*/>*/}
                    </Col>
                    <Col span={4} className="btnRight">
                        <Button icon={"save"} type='primary' style={{marginLeft: 30}}
                                onClick={this.onClickAdd.bind(this)}>新增管理员</Button>
                    </Col>
                </Row>
                <Row style={{margin: 30}}>
                    <Table
                        columns={this.columns}
                        dataSource={this.state.data}
                        scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                        columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                            const fun = () => ({style: {whiteSpace: 'nowrap'}});
                            item.onHeaderCell = fun;
                            item.onCell = fun;
                            return item;
                        })}
                        pagination={{
                            simple: false,
                            current: this.state.pageNum,
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            showTotal: (count = this.state.total) => {
                                return '共' + count + '条'
                            },
                            onChange: (current, pageSize) => {
                                this.onBaseClick(current, pageSize)
                            }
                        }}
                    />
                </Row>
                <Model data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                       onRef={this.onRef} history={this.props.history}/>

                <ResetPassword data={this.state.resetPasswordData} handleCancelReset={this.handleCancelReset} refresh={this.refresh}
                               onRef={this.onRef} history={this.props.history}/>
            </div>
        )
    }
}

export default AdministratorManagement